<?php
// +----------------------------------------------------------------------
// | [KyPHP System] Copyright (c) 2020 http://www.kuryun.com/
// +----------------------------------------------------------------------
// | [KyPHP] 并不是自由软件,你可免费使用,未经许可不能去掉KyPHP相关版权
// +----------------------------------------------------------------------
// | Author: fudaoji <fdj@kuryun.cn>
// +----------------------------------------------------------------------


namespace app\system\controller;

use app\admin\controller\FormBuilder;
use app\common\model\AdminSetting;

class Setting extends Base
{
    
    private $tabList;
    /**
     * @var AdminSetting
     */
    private $settingM;

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->settingM = new AdminSetting();
        $this->tabList = [
            'sms' => [
                'title' => '短信设置',
                'href' => url('index', ['name' => 'sms'])
            ],
        ];
    }

    /**
     * 设置
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @author: fudaoji<fdj@kuryun.cn>
     */
    public function index(){
        $current_name = input('name', 'sms');
        $setting = $this->settingM->getOneByMap(['name' => $current_name, 'uid' => $this->adminId]);
        if(request()->isPost()){
            $post_data = input('post.');
            unset($post_data['__token__']);
            if(empty($setting)){
                $res = $this->settingM->addOne([
                    'name' => $current_name,
                    'title' => $this->tabList[$current_name]['title'],
                    'value' => json_encode($post_data, JSON_UNESCAPED_UNICODE),
                    'uid' => $this->adminId
                ]);
            }else{
                $res = $this->settingM->updateOne([
                    'id' => $setting['id'],
                    'value' => json_encode($post_data, JSON_UNESCAPED_UNICODE)
                ]);
            }
            if($res){
                $this->success('保存成功');
            }else{
                $this->error('保存失败，请刷新重试', '', ['token' => request()->token()]);
            }
        }

        if(empty($setting)){
            $data = [];
        }else{
            $data = json_decode($setting['value'], true);
        }
        $builder = new FormBuilder();
        switch ($current_name){
            case 'sms':
                $builder->addFormItem('driver', 'select', '运营商', '运营商', $this->settingM->smsDrivers())
                    ->addFormItem('account', 'text', '账号/appId', '账号/appId', [], 'required maxlength=150')
                    ->addFormItem('pwd', 'text', '密码/key', '密码/key', [], 'required maxlength=150');
                break;
        }
        $builder->setFormData($data);
        return $builder->show(['tab_nav' => ['tab_list' => $this->tabList, 'current_tab' => $current_name]]);
    }
}